package com.whty.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HTTPUtil {

	public static String doGet(String url, Map<String, String> parameters, String charsetName) throws Exception {
		return doHttpRequest(url, "GET", parameters, charsetName);
	}

	public static String doPost(String url, Map<String, String> parameters, String charsetName) throws Exception {
		return doHttpRequest(url, "POST", parameters, charsetName);
	}

	public static String doHttpRequest(String url, String method, Map<String, String> parameters, String charsetName) throws Exception {

		HttpURLConnection connection = null;
		StringBuilder sb = new StringBuilder();
		try {
			connection = doHttpRequest(url, method, parameters);
			InputStream inputStream = connection.getInputStream(); // 发送请求

			int responseCode = connection.getResponseCode();
			if (responseCode != HttpURLConnection.HTTP_OK) {
				throw new Exception(connection.getResponseMessage());
			}

			BufferedReader reader;
			if (charsetName == null || "".equals(charsetName)) {
				reader = new BufferedReader(new InputStreamReader(inputStream));
			} else {
				reader = new BufferedReader(new InputStreamReader(inputStream, charsetName));
			}

			String cline = null;
			while ((cline = reader.readLine()) != null) {
				sb.append(cline);
				sb.append('\n');
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}

		return sb.toString();
	}

	private static HttpURLConnection doHttpRequest(String url, String method, Map<String, String> parameters) throws IOException {

		method = method.toUpperCase();
		String param = parseParameters(parameters);

		if (!"POST".equals(method)) {
			url += url.contains("?") ? (url.lastIndexOf("&") == url.length() - 1) ? param : "&" + param : "?" + param;
		}

		URL _url = new URL(url);		
		HttpURLConnection connection = (HttpURLConnection) _url.openConnection();

		if ("POST".equals(method)) {
			connection.setDoOutput(true);// 设置是否向httpUrlConnection输出
			connection.setRequestMethod("POST");
		}

		connection.setDoInput(true);// 设置是否从httpUrlConnection读入
		connection.setUseCaches(false);// 不使用缓存

		connection.connect();// 连接

		if ("POST".equals(method)) {
			OutputStream os = connection.getOutputStream();
			os.write(param.getBytes());
			os.flush();
			os.close();
		}

		// InputStream inputStream = connection.getInputStream(); // 发送请求

		return connection;
	}

	private static String parseParameters(Map<String, String> parameters) {
		String param = "";
		if (parameters != null) {
			Iterator<Entry<String, String>> it = parameters.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, String> et = it.next();
				String key = et.getKey();
				String value = et.getValue() == null ? "" : et.getValue();
				param += key + "=" + value + "&";
			}
			param = param.lastIndexOf("&") == param.length() - 1 ? param.substring(0, param.length() - 1) : param;
		}
		return param;
	}
	
	
}
